package com.yuyuan.common.interceptor;

import java.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import com.yuyuan.common.domain.dto.UserDTO;
import com.yuyuan.common.utils.UserHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: kestrel
 * @Version:1.0
 * @Date: 2024/6/19
 */
@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取登录用户信息
        String userInfo = request.getHeader("user-info");
        // 2.判断是否获取了用户，如果有，存入ThreadLocal
        if (StrUtil.isNotBlank(userInfo)) {
            String decodedUserDTOStringJSON = URLDecoder.decode(userInfo, "UTF-8");
            UserDTO userDTO = UserDTO.fromStringJSON(decodedUserDTOStringJSON);
            UserHolder.saveUser(userDTO);
        }
        // 3.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户
        UserHolder.removeUser();
    }
}
